// @ts-nocheck
const LOCAL_SERVER_PORT = 5174
const BASE_REST_URL = '/api/v1'

const getParamsTable = () => {
  const hash = decodeURIComponent(window.location.hash)
  const paramsString = hash.split('?')[1]
  const table = {}
  if (paramsString?.length) {
    const paramsArr = paramsString.split('&')
    paramsArr.forEach((pa) => {
      const itemArr = pa.split('=')
      if (itemArr.length === 2) {
        table[itemArr[0]] = itemArr[1]
      }
    })
  }
  if (table.localServerIp === 'clear') {
    window.sessionStorage.removeItem('localServerIpPort')
  }
  return table
}

const is_ip = (ip) => {
  var reg =
    /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
  return reg.test(ip)
}

const getLocalServerIp = () => {
  let serverIp = ''
  const reg = /^[1-9]\d*$/
  // 合法的ipv4地址才允许替换
  // 优先设置路由
  const paramsTable = getParamsTable()
  if (paramsTable.localServerIp) {
    // 判断端口
    const serverIpArr = paramsTable.localServerIp.split(':')
    if (is_ip(serverIpArr[0])) {
      serverIp = serverIpArr[0]
      const port = serverIpArr[1]
      if (port && reg.test(port)) {
        serverIp += `:${port}`
      } else {
        serverIp += `:${LOCAL_SERVER_PORT}`
      }
      window.sessionStorage.setItem('localServerIpPort', serverIp)
      return serverIp
    }
  }
  // 路由没有从sessionStorage拉取
  const sessionIp = window.sessionStorage.getItem('localServerIpPort') || ''
  const serverIpArr = sessionIp.split(':')
  if (reg.test(serverIpArr[1]) && is_ip(serverIpArr[0])) {
    serverIp = sessionIp
    return serverIp
  }
  return serverIp
}
export { getParamsTable, getLocalServerIp }
